package com.jeomo.masterdata.provider.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jeomo.base.provider.controller.BaseController;
import com.jeomo.common.core.dto.ITree;
import com.jeomo.common.core.result.CommonResult;
import com.jeomo.common.core.result.ResultCode;
import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.common.core.util.TreeUtil;
import com.jeomo.masterdata.provider.request.CreateTobRequest;
import com.jeomo.masterdata.provider.request.UpdateTobRequest;
import com.jeomo.masterdata.provider.web.vo.TobTreeVo;
import com.jeomo.masterdata.provider.web.vo.TobVo;
import com.jeomo.masterdata.starter.entity.Merchant;
import com.jeomo.masterdata.starter.entity.Tob;
import com.jeomo.masterdata.starter.exception.IntegrityConstraintViolationException;
import com.jeomo.masterdata.starter.service.IMerchantService;
import com.jeomo.masterdata.starter.service.ITobService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * <h3>jeomo</h3>
 * <p>业态controller</p>
 *
 * @author : 崔贺
 * @date : 2020-08-28 13:56
 **/
@RequestMapping("/masterData/tob")
@RestController
public class TobController extends BaseController {

    @Resource
    private ITobService tobService;

    @Resource
    private IMerchantService merchantService;

    @PostMapping
    @ApiOperation("创建业态")
    public CommonResult<String> create(@RequestBody CreateTobRequest createTobRequest) {
        try {
            Tob tob = BeanCopyUtil.copyProperties(createTobRequest, Tob.class);
            List<String> parentCode = createTobRequest.getParentCode();
            String nodeType = createTobRequest.getNodeType();
            if (nodeType == null || nodeType.isEmpty()) {
                return CommonResult.failure("未选择节点类型");
            }
            if (parentCode == null || parentCode.size() == 0) {
                if ("2".equals(nodeType)) {
                    //说明此节点类型为分组,且为根节点
                    tob.setParentCode("0");
                } else {
                    return CommonResult.failure("根节点类型必须是分组");
                }
            } else {
                tob.setParentCode(parentCode.get(parentCode.size() - 1));
            }
            tobService.create(tob);
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                throw new IntegrityConstraintViolationException();
            } else {
                e.printStackTrace();
                return CommonResult.failure("新增失败");
            }
        }
        return CommonResult.success("新增成功");
    }


    @DeleteMapping("/{code}")
    @ApiOperation("删除业态")
    public CommonResult<String> remove(@PathVariable("code") String code) {
        Boolean canTob = tobService.removeTob(code);
        if (canTob) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.failure(ResultCode.DELETE_ERROR.msg());
        }
    }

    @PutMapping
    @ApiOperation("修改业态")
    public CommonResult<String> update(@RequestBody UpdateTobRequest updateTobRequest) {
        try {
            Tob tob = BeanCopyUtil.copyProperties(updateTobRequest, Tob.class);
            tobService.updateById(tob);
        } catch (Exception e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                throw new IntegrityConstraintViolationException();
            } else {
                e.printStackTrace();
                return CommonResult.failure("修改失败");
            }
        }
        return CommonResult.success("修改成功");
    }

    @GetMapping("/{tobCode}")
    @ApiOperation("根据业态号查询业态实体")
    public CommonResult<TobVo> queryByCode(@PathVariable("tobCode") String tobCode) {
        Tob tob = tobService.getById(tobCode);
        return CommonResult.success(BeanCopyUtil.copyProperties(tob, TobVo.class));
    }

    @GetMapping("/allTree")
    @ApiOperation("获取所有业态(全部)")
    public CommonResult<List<ITree>> allTree() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        List<Tob> list = tobService.list();
        List<ITree> nodes = BeanCopyUtil.copyListProperties(list, TobTreeVo::new);
        return CommonResult.success(TreeUtil.buildTree(nodes));
    }

    @GetMapping("/tree")
    @ApiOperation("获取所有业态分组")
    public CommonResult<List<ITree>> tree() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        QueryWrapper<Tob> wrapper = new QueryWrapper<>();
        wrapper.eq("start_flag", true);
        wrapper.eq("node_type", "2");
        List<Tob> list = tobService.list(wrapper);
        List<ITree> nodes = BeanCopyUtil.copyListProperties(list, TobTreeVo::new);
        return CommonResult.success(TreeUtil.buildTree(nodes));
    }

    @GetMapping("/all")
    @ApiOperation("获取所有业态节点")
    public CommonResult<List<TobVo>> all() {
        QueryWrapper<Tob> wrapper = new QueryWrapper<>();
        wrapper.eq("start_flag", true);
        wrapper.eq("node_type", "1");
        List<Tob> list = tobService.list(wrapper);
        return CommonResult.success(BeanCopyUtil.copyListProperties(list, TobVo::new));
    }

    @PutMapping("/updateStartFlag")
    @ApiOperation("修改业态")
    public CommonResult<String> updateStartFlag(@RequestBody UpdateTobRequest updateTobRequest) {
        List<String> tobCodes = updateTobRequest.getTobCodes();
        Boolean startFlag = updateTobRequest.getStartFlag();
        if (!startFlag) {
            QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("tob_code", tobCodes);
            queryWrapper.eq("start_Flag", true);
            List<Merchant> list = merchantService.list(queryWrapper);
            if (!list.isEmpty()) {
                return CommonResult.failure("请先关闭对应商户再进行操作");
            }
        }
        UpdateWrapper<Tob> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("code", tobCodes);
        updateWrapper.set("start_Flag", startFlag);
        boolean b = tobService.update(updateWrapper);
        return b ? CommonResult.success("修改成功") : CommonResult.failure("修改失败");
    }
}
